package org.zjt.agent.generate.bytebuddy;

import org.zjt.agent.ClassDefineDescription;
import org.zjt.agent.generate.ByteCodeGenerator;
import org.zjt.agent.generate.ClassHandler;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-04 下午11:49
 * @see
 */
public class ByteBuddyByteCodeGenerator implements ByteCodeGenerator<ClassDefineDescription> {

    private final List<ClassHandler> classHandlers;

    public ByteBuddyByteCodeGenerator(List<ClassHandler> classHandlers){
        Objects.requireNonNull(classHandlers,"classHandlers is null");
        Collections.sort(classHandlers, Comparator.comparingInt(ClassHandler::order));
        this.classHandlers = classHandlers;
    }

    @Override
    public Optional<byte[]> generate(ClassDefineDescription classDefine) {
        Optional<ClassHandler> firstClassHandler = classHandlers.stream().filter(classHandler -> classHandler.support(classDefine)).findFirst();
        if (!firstClassHandler.isPresent()){
            return Optional.empty();
        }
        return firstClassHandler.get().redefine(classDefine);
    }

}
